//
//  InternationalControl.m
//  why
//
//  Created by Yinjialiang on 16/1/18.
//  Copyright © 2016年 刘赞黄Telen. All rights reserved.
//

#import "InternationalControl.h"
#import "NSObject+Telen.h"


@interface NSBundle(InternationalControl)
@end
@implementation NSBundle (InternationalControl)

+ (void)load
{
    [self swizzleSelector:@selector(localizedStringForKey:value:table:) withSelector:@selector(tl_localizedStringForKey:value:table:)];
}

- (NSString *)tl_localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)tableName
{
    if ([InternationalControl bundle]) {
        NSString* str = [[InternationalControl bundle] tl_localizedStringForKey:key value:value table:tableName];
        if (str == nil || [str isEqualToString:key]) {
            return [self tl_localizedStringForKey:key value:value table:tableName];
        }
        return str;
    }else{
        return [self tl_localizedStringForKey:key value:value table:tableName];
    }
}

@end


@implementation InternationalControl

static NSBundle *bundle = nil;

+ ( NSBundle * )bundle{
    return bundle;
}

//初始化方法
+ (void)initUserLanguage
{
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    
    NSString *language = [def valueForKey:@"userLanguage"];
    if(language.length == 0){
        NSString *path = [[NSBundle mainBundle] pathForResource:language ofType:@"lproj" ];
        bundle = [NSBundle bundleWithPath:path];
    }else{
        [self initSystemUserLanguage];
    }
}

////初始化系统方法
+(void)initSystemUserLanguage{
    
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    NSString *string = [def valueForKey:@"userLanguage"];
    if(string.length == 0){
        //获取系统当前语言版本(中文zh-Hans,英文en)
        NSArray* languages = [def objectForKey:@"AppleLanguages"];
        NSString *current = [languages objectAtIndex:0];
        string = current;
        [def setValue:current forKey:@"userLanguage"];
        [def synchronize];//持久化，不加的话不会保存
    }
    
    //获取文件路径
    NSString *path = [[NSBundle mainBundle] pathForResource:string ofType:@"lproj"];
    bundle = [NSBundle bundleWithPath:path];//生成bundle
}

//获得当前语言方法
+(NSString *)userLanguage{
    
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    NSString *language = [def valueForKey:@"userLanguage"];
    return language;
}

//设置语言方法
+(void)setUserlanguage:(NSString *)language{
    
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    
    //1.第一步改变bundle的值
    NSString *path = [[NSBundle mainBundle] pathForResource:language ofType:@"lproj" ];
    bundle = [NSBundle bundleWithPath:path];
    
    //2.持久化
    [def setValue:language forKey:@"userLanguage"];
    [def synchronize];
}

@end
